﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System.IO;
using System;

namespace nkl {

    public class ResourceManager : MonoBehaviour
    {

        public static ResourceManager Instance { get; private set; }

        public HeroBag<HeroBagItem> heroBag;
        public ItemPool<Item> itemPool;
        public EquipmentPool<Equipment> equipmentPool;

        private void Awake()
        {


            if (Instance == null)
            {
                Instance = this;
                this.loadData();
                DontDestroyOnLoad(gameObject);
            }
            else
            {
                Destroy(gameObject);
            }



        }

        private void loadData(){
            string main_heroBagPath = Application.streamingAssetsPath + "/main_heroBag.json";
            string main_itemsPath = Application.streamingAssetsPath + "/main_items.json";
            string main_equipmentsPath = Application.streamingAssetsPath + "/main_equipments.json";

            string main_heroBagJsonStr = File.ReadAllText(main_heroBagPath);
            string main_itemsJsonStr = File.ReadAllText(main_itemsPath);
            string main_equipmentsJsonStr = File.ReadAllText(main_equipmentsPath);

            Instance.heroBag = JsonMapper.ToObject<HeroBag<HeroBagItem>>(main_heroBagJsonStr);
            Instance.itemPool = JsonMapper.ToObject<ItemPool<Item>>(main_itemsJsonStr);
            Instance.equipmentPool = JsonMapper.ToObject<EquipmentPool<Equipment>>(main_equipmentsJsonStr);

            Debug.Log("数据加载完成");
        }

        /// <summary>
        /// 根据id从库里寻找
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"> id </param>
        /// <param name="itemType">物品类型</param>
        /// <returns></returns>
        public static T FindItemWithId<T>(int id, ItemType itemType)
        {
            try
            {
                if (itemType == ItemType.consumables) {
                    return (T)Convert.ChangeType(Instance.itemPool.getItem(id), typeof(T));
                }else{
                    return (T)Convert.ChangeType(Instance.equipmentPool.getItem(id), typeof(T));
                }

            }
            catch (InvalidCastException)
            {
                return default(T);
            }
            

        }
        /// <summary>
        /// 物品池是否存在该物品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool isExsitInPool(int id)
        {
            return (FindItemWithId<Item>(id, ItemType.consumables) != null || FindItemWithId<Equipment>(id, ItemType.equipment) != null);
        }

    }
}

